package com.zhihu.matisse.library.slice;

import com.zhihu.matisse.library.MatisseAbility;
import com.zhihu.matisse.library.ResourceTable;
import com.zhihu.matisse.library.component.CheckRadioView;
import com.zhihu.matisse.library.component.CheckView;
import com.zhihu.matisse.library.model.IncapableCause;
import com.zhihu.matisse.library.model.Item;
import com.zhihu.matisse.library.model.SelectedItemCollection;
import com.zhihu.matisse.library.model.SelectionSpec;
import com.zhihu.matisse.library.provider.PreviewProvider;
import com.zhihu.matisse.library.utils.IncapableDialog;
import com.zhihu.matisse.library.utils.L;
import com.zhihu.matisse.library.utils.PhotoMetadataUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.PageSlider;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.PacMap;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.util.ArrayList;

import static com.zhihu.matisse.library.model.SelectedItemCollection.STATE_COLLECTION_TYPE;
import static com.zhihu.matisse.library.model.SelectedItemCollection.STATE_SELECTION;

public class BasePreviewAbility extends Ability implements PageSlider.PageChangedListener{
    public static final String EXTRA_DEFAULT_BUNDLE = "extra_default_bundle";
    public static final String EXTRA_RESULT_BUNDLE = "extra_result_bundle";
    public static final String EXTRA_RESULT_APPLY = "extra_result_apply";
    public static final String EXTRA_RESULT_ORIGINAL_ENABLE = "extra_result_original_enable";
    public static final String CHECK_STATE = "checkState";

    protected final SelectedItemCollection mSelectedCollection = new SelectedItemCollection(this);
    protected SelectionSpec mSpec;


    protected Text tvBack,tvApply,mSize,tvOriginal;
    private CheckRadioView cbOriginal;
    protected CheckView mCheckView;
    private DirectionalLayout dlCheck;
    protected PageSlider pageSlider;

    private boolean mIsToolbarHide = false;
    protected int mPreviousPos = -1;
    protected boolean mOriginalEnable;

    protected PreviewProvider previewProvider;

    private int mSelectedColor = 0x1E8AE8;
    private int mUnSelectUdColor = 0x808080;

//    @Override
//    public void onRestoreAbilityState(PacMap inState) {
//        super.onRestoreAbilityState(inState);
//        mSelectedCollection.onCreate( inState);
//        mOriginalEnable = inState.getBooleanValue("checkState");
//    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        if (!SelectionSpec.getInstance().hasInited) {
            terminateAbility(0);
            return;
        }
        setUIContent(ResourceTable.Layout_ability_preview);
        mSpec = SelectionSpec.getInstance();
        if (mSpec.needOrientationRestriction()) {
            setDisplayOrientation(mSpec.orientation);
        }

        if (intent == null) {
            mSelectedCollection.onCreate(getIntent());
            mOriginalEnable = getIntent().getBooleanParam(EXTRA_RESULT_ORIGINAL_ENABLE, false);
        } else {
//            PacMap pacMap = getIntent().getParcelableParam(EXTRA_DEFAULT_BUNDLE);
            mSelectedCollection.onCreate(intent);
            mOriginalEnable = getIntent().getBooleanParam(EXTRA_RESULT_ORIGINAL_ENABLE,false);
        }

        tvBack = (Text) findComponentById(ResourceTable.Id_textPreview_back);
        tvApply = (Text) findComponentById(ResourceTable.Id_textPreview_apply);
        mSize = (Text) findComponentById(ResourceTable.Id_textPreview_size);
        tvOriginal = (Text) findComponentById(ResourceTable.Id_textPreview_original);
        cbOriginal = (CheckRadioView) findComponentById(ResourceTable.Id_checkPreview_radio);
        mCheckView = (CheckView) findComponentById(ResourceTable.Id_checkPreview);
        mCheckView.setCountable(mSpec.countable);
        dlCheck = (DirectionalLayout) findComponentById(ResourceTable.Id_dlPreview_check);
        pageSlider = (PageSlider) findComponentById(ResourceTable.Id_sliderPreview);
        pageSlider.setOrientation(Component.HORIZONTAL);
        pageSlider.addPageChangedListener(this);
        try {
            mSelectedColor = getContext().getResourceManager().getElement(ResourceTable.Color_zhihu_item_checkCircle_backgroundColor).getColor();
            mUnSelectUdColor = getContext().getResourceManager().getElement(ResourceTable.Color_zhihu_check_original_radio_disable).getColor();
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }


        tvBack.setClickedListener(component -> parseClick(component,0));
        tvApply.setClickedListener(component -> parseClick(component,3));

        mCheckView.setClickedListener(component -> parseClick(component,1));
        dlCheck.setClickedListener(component -> parseClick(component,2));

        previewProvider = new PreviewProvider(this,new ArrayList<>());
        pageSlider.setProvider(previewProvider);
        previewProvider.setOnPrimaryItemSetListener(new PreviewProvider.OnPrimaryItemSetListener() {
            @Override
            public void onPrimaryItemSet(int position, Uri uri) {
                L.d("视频启动 《=======================》" + uri);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PLAY);
                intent.setUriAndType(uri,"video/*");
                try {
                    startAbility(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        updateApplyButton();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        mSelectedCollection.onSaveInstanceState( outState);
        outState.putBooleanValue("checkState", mOriginalEnable);
        super.onSaveAbilityState(outState);
    }

    @Override
    protected void onBackPressed() {
//        sendBackResult(false);
        super.onBackPressed();
    }

    private void parseClick(Component component, int index){
        switch (index){
            case 0:
                onBackPressed();
                break;
            case 3:
                sendBackResult(true);
                terminateAbility();
                break;
            case 1:
                Item item = previewProvider.getMediaItem(pageSlider.getCurrentPage());
                if (mSelectedCollection.isSelected(item)) {
                    mSelectedCollection.remove(item);
                    if (mSpec.countable) {
                        mCheckView.setCheckedNum(CheckView.UNCHECKED);
                    } else {
                        mCheckView.setChecked(false);
                    }
                } else {
                    if (assertAddSelection(item)) {
                        mSelectedCollection.add(item);
                        if (mSpec.countable) {
                            mCheckView.setCheckedNum(mSelectedCollection.checkedNumOf(item));
                        } else {
                            mCheckView.setChecked(true);
                        }
                    }
                }
                updateApplyButton();

                if (mSpec.onSelectedListener != null) {
                    mSpec.onSelectedListener.onSelected(
                            mSelectedCollection.asListOfUri(), mSelectedCollection.asListOfString());
                }
                break;

            case 2:
                mOriginalEnable = !mOriginalEnable;
                cbOriginal.setChecked(mOriginalEnable);
                tvOriginal.setTextColor(new Color(mOriginalEnable ? mSelectedColor : mUnSelectUdColor));
                break;
            default:
                break;
        }
    }

    private void updateApplyButton() {
        int selectedCount = mSelectedCollection.count();
        if (selectedCount == 0) {
            try {
                tvApply.setText(getResourceManager().getElement(ResourceTable.String_button_apply_default).getString());
                tvApply.setTextColor(new Color(getResourceManager().getElement(ResourceTable.Color_zhihu_bottom_toolbar_apply_text_disable).getColor()));
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
                tvApply.setText("Apply");
            }

            tvApply.setEnabled(false);
        } else if (selectedCount == 1 && mSpec.singleSelectionModeEnabled()) {
            try {
                tvApply.setText(getResourceManager().getElement(ResourceTable.String_button_apply_default).getString());
                tvApply.setTextColor(new Color(getResourceManager().getElement(ResourceTable.Color_zhihu_bottom_toolbar_apply_text).getColor()));
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
                tvApply.setText("Apply");
            }
            tvApply.setEnabled(true);
        } else {
            tvApply.setEnabled(true);
            try {
                tvApply.setText(getResourceManager().getElement(ResourceTable.String_button_apply).getString(selectedCount));
                tvApply.setTextColor(new Color(getResourceManager().getElement(ResourceTable.Color_zhihu_bottom_toolbar_apply_text).getColor()));
            } catch (IOException | NotExistException | WrongTypeException e) {
                e.printStackTrace();
            }
        }

        if (mSpec.originalable) {
            dlCheck.setVisibility(Component.VISIBLE);
            updateOriginalState();
        } else {
            dlCheck.setVisibility(Component.HIDE);
        }
    }


    private void updateOriginalState() {
        cbOriginal.setChecked(mOriginalEnable);
        if (!mOriginalEnable) {
            cbOriginal.setColor(Color.WHITE);
        }

        if (countOverMaxSize() > 0) {

            if (mOriginalEnable) {
                IncapableDialog incapableDialog = new IncapableDialog(getContext());
                try {
                    incapableDialog.setMessage(getResourceManager().getElement(ResourceTable.String_error_over_original_size).getString(mSpec.originalMaxSize));
                } catch (IOException | NotExistException | WrongTypeException e) {
                    e.printStackTrace();
                    incapableDialog.setMessage(String.format("Can\\'t select the images larger than %1$d MB",mSpec.originalMaxSize));
                }
                incapableDialog.show();

                cbOriginal.setChecked(false);
                cbOriginal.setColor(Color.WHITE);
                mOriginalEnable = false;
            }
        }
    }


    private int countOverMaxSize() {
        int count = 0;
        int selectedCount = mSelectedCollection.count();
        for (int i = 0; i < selectedCount; i++) {
            Item item = mSelectedCollection.asList().get(i);
            if (item.isImage()) {
                float size = PhotoMetadataUtils.getSizeInMB(item.size);
                if (size > mSpec.originalMaxSize) {
                    count++;
                }
            }
        }
        return count;
    }

    protected void updateSize(Item item) {
        if (item.isGif()) {
            mSize.setVisibility(Component.VISIBLE);
            mSize.setText(PhotoMetadataUtils.getSizeInMB(item.size) + "M");
        } else {
            mSize.setVisibility(Component.HIDE);
        }

        if (item.isVideo()) {
            dlCheck.setVisibility(Component.HIDE);
        } else if (mSpec.originalable) {
            dlCheck.setVisibility(Component.VISIBLE);
        }
    }

    protected void sendBackResult(boolean apply) {
        Intent intent = new Intent();
        intent.setParcelableArrayListParam(STATE_SELECTION, new ArrayList<>(mSelectedCollection.getItems()));
        intent.setParam(STATE_COLLECTION_TYPE, mSelectedCollection.getCollectionType());
        intent.setParam(EXTRA_RESULT_APPLY, apply);
        intent.setParam(EXTRA_RESULT_ORIGINAL_ENABLE, mOriginalEnable);
        setResult(MatisseAbility.RESULT_OK, intent);
    }

    private boolean assertAddSelection(Item item) {
        IncapableCause cause = mSelectedCollection.isAcceptable(item);
        IncapableCause.handleCause(this, cause);
        return cause == null;
    }

    @Override
    public void onPageSliding(int i, float v, int i1) {

    }

    @Override
    public void onPageSlideStateChanged(int position) {

    }

    @Override
    public void onPageChosen(int position) {
        PreviewProvider adapter = (PreviewProvider) pageSlider.getProvider();
        if (mPreviousPos != -1 && mPreviousPos != position) {
//            ( adapter.createPageInContainer(pageSlider, mPreviousPos)).resetView();

            Item item = adapter.getMediaItem(position);
            if (mSpec.countable) {
                int checkedNum = mSelectedCollection.checkedNumOf(item);
                mCheckView.setCheckedNum(checkedNum);
                if (checkedNum > 0) {
                    mCheckView.setEnabled(true);
                } else {
                    mCheckView.setEnabled(!mSelectedCollection.maxSelectableReached());
                }
            } else {
                boolean checked = mSelectedCollection.isSelected(item);
                mCheckView.setChecked(checked);
                if (checked) {
                    mCheckView.setEnabled(true);
                } else {
                    mCheckView.setEnabled(!mSelectedCollection.maxSelectableReached());
                }
            }
            updateSize(item);
        }
        mPreviousPos = position;
    }
}
